package com.ttxs.generator.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Map;

@Slf4j
public class ObjectMapperUtils {
    private static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static <T> T readValue(String from, Class<T> toValueType) {
        try {
            return objectMapper.readValue(from, toValueType);
        } catch (JsonProcessingException e) {
            log.warn(e.getMessage(), e);
        }
        return null;
    }

    public static <T> T readValue(String from, TypeReference<T> toValueTypeRef) {
        try {
            return objectMapper.readValue(from, toValueTypeRef);
        } catch (JsonProcessingException e) {
            log.warn(e.getMessage(), e);
        }
        return null;
    }

    public static <T> T convert(Object fromValue, TypeReference<T> toValueTypeRef) {
        return objectMapper.convertValue(fromValue, toValueTypeRef);
    }

    public static <T> T convert(Object fromValue, Class<T> toValueType) {
        if (toValueType == Void.class) {
            return null;
        }
        return objectMapper.convertValue(fromValue, toValueType);
    }

    public static Map<String, Object> toMap(Object fromValue) {
        return objectMapper.convertValue(fromValue, new TypeReference<Map<String, Object>>() {
        });
    }

    public static MultiValueMap<String, Object> toMultiValueMap(Object fromValue) {
        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        toMap(fromValue).forEach((key, value) -> {
            multiValueMap.add(key, value);
        });
        return multiValueMap;
    }

}
